package com.lcredu.web.json;

import com.lcredu.web.json.entity.Dog;
import com.lcredu.web.json.entity.Person;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * @author 黎长容
 * @date 2025-07-23 16:56
 */
//@Controller
//@ResponseBody
@RestController
public class DogHandle {

    //获取一条狗的json对象
//    @ResponseBody
    @RequestMapping("/json/getDog")
    private Dog getDog() {
        Dog dog = new Dog("小白", 2);
        return dog;
    }


    //    @ResponseBody
    @RequestMapping("/json/save2")
    private Person save(@RequestBody Person person) {
        System.out.println(person);
        return person;
    }

    //如果返回多个对象(数组)
//    @ResponseBody
    @RequestMapping("json/dogs")
    public List<Dog> getDogs() {
        Dog dog1 = new Dog("小白", 1);
        Dog dog2 = new Dog("小白", 1);
        Dog dog3 = new Dog("小白", 1);
        Dog dog4 = new Dog("小白", 1);
        Dog[] dogs = {dog1, dog2, dog3, dog4};
        return Arrays.asList(dogs);
    }


    //来一个文件下载

    /**
     * 黎长容知识
     * public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status)
     *      T body ; 要下载的数据
     *      MultiValueMap<String, String> headers : 接口,可以用实现子类HttpHeaders
     *      HttpStatus status : 响应状态码
     * 1. 返回一个ResponseEntity<byte[]>二进制返回,在返回时httpMessageConvert会用二进制返回
     *
     * @return
     */
    @RequestMapping("/downFile")
    public ResponseEntity<byte[]> downFile(HttpSession session) throws IOException {
        //文件输入流
        InputStream resourceAsStream = session.getServletContext().getResourceAsStream("/text/1.txt");
        int available = resourceAsStream.available();
        byte[] bytes = new byte[available];
        //读取
        resourceAsStream.read(bytes);


        //2.创建响应头
        //根据 http 协议这个就是告诉浏览器，这是返回的一个文件,浏览器就弹出小窗口
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=1.txt");

        //3.返回成功的响应码
        HttpStatus httpStatus = HttpStatus.OK;

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, httpStatus);

        return responseEntity;
    }
}
